package com.example.springbootlogin.controller;

import com.example.springbootlogin.annotation.AuthAccess;
import com.example.springbootlogin.domain.User;
import com.example.springbootlogin.service.UserService;
import com.example.springbootlogin.utils.Result;
import com.example.springbootlogin.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    
    @Resource
    private TokenUtils tokenUtils;

    @AuthAccess // 登录接口不需要验证token
    @PostMapping("/login")
    public Result<User> loginController(@RequestParam String uname, @RequestParam String password){
        User user = userService.loginService(uname, password);
        if(user!=null){
            // 生成token
            String token = tokenUtils.genToken(user.getUid(), user.getPassword());
            user.setToken(token);
            return Result.success(user,"登录成功！");
        }else{
            return Result.error("123","账号或密码错误！");
        }
    }

    @AuthAccess // 注册接口不需要验证token
    @PostMapping("/register")
    public Result<User> registController(@RequestBody User newUser){
        User user = userService.registService(newUser);
        if(user!=null){
            return Result.success(user,"注册成功！");
        }else{
            return Result.error("456","用户名已存在！");
        }
    }
    
    // 添加获取所有用户的接口，需要token验证
    @GetMapping("/selectAll")
    public Result<List<User>> selectAll() {
        List<User> users = userService.selectAllUsers();
        return Result.success(users, "获取用户列表成功");
    }
    
    // 获取当前用户信息
    @GetMapping("/getCurrentUser")
    public Result<User> getCurrentUser() {
        User currentUser = tokenUtils.getCurrentUser();
        if (currentUser != null) {
            currentUser.setPassword(""); // 不返回密码
            return Result.success(currentUser, "获取当前用户成功");
        } else {
            return Result.error("401", "未登录或token已过期");
        }
    }
}